import React, { Component, Fragment } from 'react';
import styles from './InterviewResult.less';
import {
  LeftOutlined,
  PlusOutlined
} from '@ant-design/icons';
import { Row, Col, notification, Upload, Modal } from 'antd';
import { history } from 'umi';
import request from '@/utils/request'
import moment from 'moment'
import PublicUtils from "@/utils/publicUtils";
import pendUser from '@/assets/pendUser.png';
import {
  Form,
  TextArea,
  ImageViewer,
  Button
} from 'antd-mobile'


export default class abandon extends Component {
  constructor(props) {
    super(props);
    this.state = {
      title: '放弃入职',
      staffId: '',
      userInfo: JSON.parse(window.localStorage.getItem('userInfo')),
      fileList: [], // 放弃附件
      previewImage: '', // 预览图片
      fileIdList: [], //附件Id
      previewVisible: false, // 预览弹框
    }
    this.formRef = React.createRef();
  }

  componentDidMount() {
    const queryParams = new URLSearchParams(history.location.search);
    const staffId = queryParams.get('staffId');
    this.setState({
      staffId: staffId,
    })
  }


  beforeUpload = (file) => {
    if (file.name) {
      const typeList = ['doc', 'docx', 'pdf', 'jpeg', 'jpg', 'png', 'eml']
      let fileNameArr = file.name.split('.')
      if (fileNameArr.length > 0) {
        let fileType = fileNameArr[fileNameArr.length - 1]
        const type = fileType.toLowerCase()
        let isCanUpload = typeList.some(item => type.includes(item))
        if (isCanUpload) {
          const isLt5M = file.size / 1024 / 1024 < 5;
          if (!isLt5M) {
            notification.error({
              message: '文件不得大于5MB!'
            })
            return false
          }
        } else {
          notification.error({
            message: '上传文件格式不正确'
          })
          return false
        }
      }
    }
    return true
  }


  // 图片上传成功回调
  onSuccess = (res, file) => {
    const { fileIdList } = this.state;
    if (res && res.error_code === 200) {
      let ids = fileIdList.concat([res.data[0].fileId]);
      this.setState({ fileIdList: ids }, () => {
        this.getFileList(26);
      });
    } else {
      notification.error({
        message: res ? res.error_msg : '请求错误'
      });
    }
  }

  // 图片上传失败回调
  onError = () => {
    notification.error({
      message: '网络错误'
    })
  }

  // 删除文件
  deleteFile = (file) => {
    const _this = this
    confirm({
      title: '确定删除该文件？',
      okText: '删除',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        request.delete('/sysFile/delete', {
          params: {
            fileId: file.fileId
          }
        }).then(res => {
          if (res && res.error_code === 200) {
            notification.success({
              message: '文件已删除'
            })
            let ids = _this.state.fileIdList.filter(item => item !== file.fileId);
            _this.setState(
              {
                fileIdList: ids
              },
              () => {
                _this.getFileList(26);
              }
            );
          } else {
            notification.error({
              message: res ? res.error_msg : '请求错误'
            })
          }
        })
      }
    })
    return false
  }


  // 预览图片
  handlePreview = file => {
    let url = file.url || file.filePath;
    let index = url.lastIndexOf(".");
    //获取后缀
    let ext = url.substr(index + 1);
    let format = ['jpg', 'jpeg', 'png'];
    if (format.includes(ext)) {
      this.setState({
        previewImage: url,
        previewVisible: true
      })
    } else {
      window.open(url)
    }
  }

  // 拒绝入职文件列表
  getFileList = (fileType) => {
    const { staffId, fileIdList } = this.state;
    console.log(fileType);
    request
      .get('/sysFile/list', {
        params: {
          fileType,
          belongObj: 0, // 0-员工，1-人才，2-项目，3-公司
          belongId: staffId,
          fileList: fileIdList.length && fileIdList.join(',')
        }
      })
      .then(res => {
        if (res && res.error_code === 200) {
          const fileServerData = res.data ? res.data : [];
          let newFiles = fileServerData.map(item => {
            return {
              ...item,
              uid: item.fileId,
              name: item.fileName,
              status: 'done',
              url: item.filePath
            };
          });
          this.setState({ fileList: newFiles });
        } else {
          notification.error({
            message: res ? res.error_msg : '请求错误'
          });
        }
      });
  };

  onFinish = values => {
    console.log('Success:', values);
    const { staffId, fileIdList } = this.state;
    this.formRef.current.validateFields(['onboardingFailureReason'])
      .then(values => {
        request.post('/staff/refuseJoin', {
          data: {
              staffId: staffId,
              onboardingFailureReason: values.onboardingFailureReason,
              fileList: fileIdList.length && fileIdList.join(',')
          }
      }).then(res => {
          if (res && res.error_code === 200) {
              notification.success({ message: '操作成功' });
              this.setState({ fileList: [] },()=>{
                history.go(-1)
              })
              this.formRef.current.resetFields();
          } else {
              notification.error({
                  message: res ? res.error_msg : '请求错误'
              })
          }
      })
      })
  }

  // 预览图片关闭弹窗
  handleCancelModel = () => this.setState({ previewVisible: false })


  render() {
    const {
      title,
      userInfo,
      fileList,
      staffId,
      previewVisible,
      previewImage
    } = this.state;

    const uploadButton = (
      <div >
        <PlusOutlined />
        <div style={{ marginTop: 10 }} className="ant-upload-text">上传附件</div>
      </div>
    );

    return (
      <div className={styles.contain}>
        <div className={styles.headerTitle}>
          <Row style={{ width: '100%', height: '100%', justifyContent: 'center', alignItems: 'center' }}>
            <Col style={{ marginLeft: '20px', fontSize: '18px', color: '#409EFF' }} onClick={() => history.go(-1)}>
              <LeftOutlined style={{ fontSize: '20px', color: '#409EFF' }} />返回
            </Col>
            <Col offset={20} style={{ marginLeft: '25px', flexGrow: 1 }}>
              <div style={{ fontSize: '18px', color: '#333333', fontWeight: 'bold' }}>{title}</div>
            </Col>
          </Row>
        </div>
        <div className={`${styles.context}`}>
          <div className={styles.baseName}>
            <div className={styles.name}>{userInfo?.staffName}</div>
            <div className={styles.develName}>{userInfo?.staffJobName}{' / ' + userInfo?.levelName}</div>
            <div className={styles.icon} style={{ position: 'relative' }}>
              <img src={pendUser} alt="pendUser" style={{ width: '40px', height: '35px' }}></img>
              <div style={{ fontSize: '18px', height: '35px', display: 'flex', alignItems: 'center' }}>待入职</div>
            </div>
          </div>
          <div className={styles.baseInfo}>
            <Form layout='vertical' onFinish={this.onFinish} mode='card' ref={this.formRef} footer={
              <div style={{width:'100%',display: 'flex', justifyContent: 'center', alignItems: 'center'}}>
                <Button onClick={() => history.go(-1)}  color='primary' fill='outline' size='middle' style={{ padding: '15px 60px', marginRight: '20px' }}>
                取消
              </Button>
              <Button type='submit' color='primary' fill='solid' size='middle' style={{ padding: '15px 60px' }}>
                确定
              </Button>
              </div>
            }>
              <Form.Item label='失败原因' name='onboardingFailureReason'
                rules={[
                  { required: true, message: '请输入失败原因' },
                  { max: 200, message: '失败原因内容超出限定范围（200字）' }
                ]}
              >
                <TextArea
                  style={{ marginTop: '20px' }}
                  allowClear
                  rows={6}
                  placeholder='请填写失败原因'
                  showCount
                  minLength={0}
                  maxLength={200}
                />
              </Form.Item>
              <Form.Item
                label='相关附件'
              >
                <Upload
                  fileList={fileList}
                  accept='image/*,.doc,.docx,.pdf,.eml'
                  action="/api/sysFile/upload"
                  name="files"
                  data={{ fileType: 26, belongObj: 0, belongId: staffId }}
                  headers={{
                    'x-token': window.localStorage.getItem('x-token'),
                    Perms: window.location.pathname ? window.location.pathname.replace(/^#/, '') : ''
                  }}
                  listType="picture-card"
                  beforeUpload={this.beforeUpload}
                  onSuccess={(res, file) => this.onSuccess(res, file)}
                  onError={this.onError}
                  onRemove={(file) => this.deleteFile(file)}
                  onPreview={this.handlePreview}
                >
                  {fileList.length >= 9 ? null : uploadButton}
                </Upload>
              </Form.Item>
            </Form>
            {/* 图片预览 */}
            <ImageViewer
              classNames={{
                mask: 'customize-mask',
                body: 'customize-body',
              }}
              image={previewImage}
              visible={previewVisible}
              onClose={() => {
                this.setState({ previewVisible: false })
              }}
            />
          </div>
        </div>
      </div>
    )
  }

}